package hk.com.fgoproduction.getdroplets.BroadcastAndNoti

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import hk.com.fgoproduction.getdroplets.Lib.Common.ToolInstance.ToastInstance
import hk.com.fgoproduction.getdroplets.Service.FileCompareService
import hk.com.fgoproduction.getdroplets.Service.FileVerValService
import hk.com.fgoproduction.getdroplets.Service.IOService

class NotiReceiver : BroadcastReceiver() {

    companion object {
        val NOTI_TAG_IO = "hk.com.fgoproduction.getdroplets.BroadcastAndNoti.noti_tag.io"
        val NOTI_TAG_VER = "hk.com.fgoproduction.getdroplets.BroadcastAndNoti.noti_tag.ver"
        val ACTION_CANCEL = 0xC4
        private var receiverInstance: NotiReceiver? = null
        private var ctx: Context? = null
        private var intent: IntentFilter? = null
        private val lock = Any()

        fun receiverFactory(ctx: Context, intent: IntentFilter, action: String? = null): NotiReceiver {
            if (receiverInstance == null) {
                synchronized(lock) {
                    if (receiverInstance == null) {
                        receiverInstance = NotiReceiver()
                        this.ctx = ctx
                        this.intent = intent
                        if (action != null)
                            intent.addAction(action)
                    }
                }
            }

            return receiverInstance as NotiReceiver
        }

        fun clearInstance() {
            receiverInstance = null
        }
    }

    var isListening = false

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent!!.action == NOTI_TAG_IO) {
            val bundle = intent.extras
            val serviceIntent = Intent(context, IOService::class.java)
            serviceIntent.putExtras(bundle)
            when (bundle.getInt("id")) {
                0 -> {
                    context?.stopService(serviceIntent)
                    ToastInstance.show(ctx as Context, "Finish")
                }
                else -> context?.startService(serviceIntent)
            }
        } else if (intent.action == NOTI_TAG_VER) {
            val verIntent = Intent(context, FileCompareService::class.java)
            verIntent.putExtra("path", intent.getStringExtra("path"))
            verIntent.putExtra("localPath", intent.getStringExtra("localPath"))
            context?.startService(verIntent)
        }
    }

    fun startListening(action: String?) {
        if (action == null)
            return
        else
            intent?.addAction(action)
        ctx?.registerReceiver(receiverInstance, intent) ?: Exception("$ctx")
        isListening = true
    }

    fun stopListening() {
        ctx?.unregisterReceiver(receiverInstance)
        isListening = false
    }
}